﻿#region Header
// ------------------------ Licence / Copyright ------------------------
// 
// ScrumTable for Scrum Meeting Support
// Copyright © HSR - Hochschule für Technik Rapperswil
// All Rights Reserved
// 
// Author:
//  Michael Gfeller Silvan Gehrig Patrick Boos
// 
// ---------------------------------------------------------------------
#endregion

#region Usings

using System;
using System.Collections.Generic;
using ScrumTable.Common.Text;

#endregion

namespace ScrumTable.Common.Collections
{
    /// <summary>
    /// Specifies a chain of keys which corresponds, when joined, to a unqiue value.
    /// </summary>
    /// <remarks>
    /// A chain is formated as follows:
    ///  Id1 # Id2 # Id2
    ///   OR
    ///  Id1.1 # Id1.2 # Id1.2, Id2.1 # Id2.2 # Id2.2
    /// </remarks>
    public class ValueChain<T> : IEnumerable<T>, IEquatable<ValueChain<T>>, IComparable<ValueChain<T>>
        where T : class
    {
        #region Declarations
        //--------------------------------------------------------------------
        // Declarations
        //--------------------------------------------------------------------

        /// <summary>
        /// Gets an empty value chain instance.
        /// </summary>
        public static readonly ValueChain<T> Empty = new ValueChain<T>();

        /// <summary>
        /// Gets the internal value separator.
        /// </summary>
        internal static readonly string[] ValueSeparator = new[] { " # " };

        private readonly List<T> _keys = new List<T>(0);
        private string _fullChain;
        private ValueChain<T> _parentChain;
        
        #endregion

        #region Properties
        //--------------------------------------------------------------------
        // Properties
        //--------------------------------------------------------------------

        /// <summary>
        /// Gets the value at the given chain index.
        /// </summary>
        /// <param name="index">Index of the value to retrieve.</param>
        /// <returns>Returns the retrieved value.</returns>
        public T this[int index]
        {
            get
            {
                PreCondition.AssertInRange(-1, _keys.Count, index, "index");
                return _keys[index];
            }
        }

        /// <summary>
        /// Gets the number of values stored in the current collection.
        /// </summary>
        public int Count
        {
            get { return _keys.Count; }
        }

        /// <summary>
        /// Gets the value chain as string of the current instance.
        /// </summary>
        public string Chain
        {
            get
            {
                if (_fullChain == null)
                {
                    _fullChain = StringUtil.Join(_keys, ValueSeparator[0]);
                }
                return _fullChain;
            }
        }

        /// <summary>
        /// Returns true if the current value chain is empty.
        /// </summary>
        public bool IsEmpty
        {
            get { return (Count == 0); }
        }

        /// <summary>
        /// Gets the top value. This represents the value on the right side of the chain.
        /// </summary>
        public T Top
        {
            get { return (_keys.Count > 0) ? _keys[_keys.Count - 1] : DefaultValue; }
        }

        /// <summary>
        /// Gets the bottom value. This represents the value on the left side of the chain.
        /// </summary>
        public T Bottom
        {
            get { return (_keys.Count > 0) ? _keys[0] : DefaultValue; }
        }

        /// <summary>
        /// Gets the parent chain specified.
        /// </summary>
        public ValueChain<T> ParentChain
        {
            get
            {
                if (_parentChain == null)
                {
                    if (_keys.Count > 0)
                        _parentChain = new ValueChain<T>(_keys.GetRange(0, _keys.Count - 1));
                    else
                        _parentChain = Empty;
                }
                return _parentChain;
            }
        }

        /// <summary>
        /// Gets all contained parent chains in the current value chain.
        /// </summary>
        public IEnumerable<ValueChain<T>> ContainedChains
        {
            get
            {
                for (int i = 1; i < _keys.Count + 1; ++i)
                {
                    yield return new ValueChain<T>(_keys.GetRange(0, i));
                }
            }
        }

        /// <summary>
        /// Returns the default value. This property may be overwritten in
        /// derived classes such as string.
        /// </summary>
        protected virtual T DefaultValue
        {
            get { return GetDefaultValue(); }
        }

        #endregion

        #region Constructors / Destructor
        //--------------------------------------------------------------------
        // Constructors / Destructor
        //--------------------------------------------------------------------

        /// <summary>
        /// Creates a new ValueChain instance with the specified data.
        /// </summary>
        public ValueChain()
        {
        }

        /// <summary>
        /// Creates a new ValueChain instance with the specified data.
        /// </summary>
        /// <param name="valueChain">Specifies the values stored in the current chain.</param>
        public ValueChain(params T[] valueChain)
            : this((IEnumerable<T>)valueChain)
        {
        }

        /// <summary>
        /// Creates a new ValueChain instance with the specified data.
        /// </summary>
        /// <param name="valueChain">Specifies the values stored in the current chain.</param>
        /// <param name="additionalValue">Specifies the value which is inserted at the top of the chain.</param>
        public ValueChain(IEnumerable<T> valueChain, T additionalValue)
            : this(valueChain)
        {
            if (additionalValue != null)
            {
                _keys.Add(additionalValue);
            }
        }

        /// <summary>
        /// Creates a new ValueChain instance with the specified data.
        /// </summary>
        /// <param name="valueChain">Specifies the values stored in the current chain.</param>
        public ValueChain(IEnumerable<T> valueChain)
        {
            if (valueChain != null)
            {
                _keys.AddRange(valueChain);
            }
        }

        /// <summary>
        /// Creates a new ValueChain instance with the specified data.
        /// </summary>
        /// <param name="valueChain">Specifies the values stored in the current chain.</param>
        /// <param name="additionalValue">Specifies the value which is inserted at the top of the chain.</param>
        public ValueChain(ValueChain<T> valueChain, T additionalValue)
        {
            _parentChain = valueChain;

            if (_parentChain != null && _parentChain != Empty)
            {
                _keys.AddRange(_parentChain._keys);
            }
            _keys.Add(additionalValue);
        }

        #endregion

        #region Methods
        //--------------------------------------------------------------------
        // Methods
        //--------------------------------------------------------------------

        /// <summary>
        /// Gets the default value for the current ValueChain type.
        /// </summary>
        /// <returns>Returns the evaluated default value.</returns>
        internal static T GetDefaultValue()
        {
            if (typeof(T) == typeof(string))
                return (T)((object)(string.Empty));
            return default(T);
        }

        /// <summary>
        /// Returns true, if the given value chain is null or empty.
        /// </summary>
        /// <param name="toCheck">ValueChain instance to check for emptiness.</param>
        /// <returns>Returns true, if the given value chain is null or empty.</returns>
        public static bool IsNullOrEmpty(ValueChain<T> toCheck)
        {
            return (toCheck == null || toCheck._keys.Count == 0);
        }

        /// <summary>
        /// Implements the operator ==.
        /// </summary>
        /// <param name="left">Specifies the left object.</param>
        /// <param name="right">Specifies the right object.</param>
        /// <returns>The result of the operator.</returns>
        public static bool operator ==(ValueChain<T> left, ValueChain<T> right)
        {
            // If both are null, or both are same instance, return true.
            if (ReferenceEquals(left, right))
            {
                return true;
            }

            // If one is null, but not both, return false.
            if ((object)left == null || (object)right == null)
            {
                return false;
            }

            // Return true if the fields match:
            return left.Equals(right);
        }

        /// <summary>
        /// Implements the operator !=.
        /// </summary>
        /// <param name="left">Specifies the left object.</param>
        /// <param name="right">Specifies the right object.</param>
        /// <returns>The result of the operator.</returns>
        public static bool operator !=(ValueChain<T> left, ValueChain<T> right)
        {
            return !(left == right);
        }

        /// <summary>
        /// Determines whether the specified IDataObject is equal to the current object.
        /// </summary>
        /// <param name="toCompare">Parameter to check.</param>
        /// <returns>Returns true if the objects are equal.</returns>
        public override bool Equals(object toCompare)
        {
            // If parameter cannot be cast to DomainBase return false.
            return Equals(toCompare as ValueChain<T>);
        }

        /// <summary>
        /// Determines whether the specified IDataObject is equal to the current object.
        /// </summary>
        /// <param name="obj">Parameter to check.</param>
        /// <returns>Returns true if the objects are equal.</returns>
        public bool Equals(ValueChain<T> obj)
        {
            // If parameter is null return false:
            if ((object)obj == null) // force compiler to use Object::operator==()
                return false;

            if (obj._keys.Count != _keys.Count)
                return false;

            for (int i = 0; i < _keys.Count; ++i)
            {
                if (!Compare(obj._keys[i], _keys[i]))
                    return false;
            }
            return true;
        }

        /// <summary>
        /// Returns the hash code for this IDataObject.
        /// </summary>
        /// <returns>Returns the computed hash value.</returns>
        public override int GetHashCode()
        {
            return Chain.GetHashCode();
        }

        /// <summary>
        /// Tries to retrieve the given value.
        /// </summary>
        /// <param name="index">Index of the value to retrieve.</param>
        /// <returns>Returns the retrieved value or an empty string.</returns>
        public T TryGetValue(int index)
        {
            if (index > -1 && index < _keys.Count)
                return _keys[index];
            return DefaultValue;
        }

        /// <summary>
        /// Returns a <see cref="System.String"/> that represents this instance.
        /// </summary>
        /// <returns>
        /// A <see cref="System.String"/> that represents this instance.
        /// </returns>
        public override string ToString()
        {
            return string.Format("{0} [{1}]", base.ToString(), Serialize());
        }

        /// <summary>
        /// Returns an enumerator that iterates through a collection.
        /// </summary>
        /// <returns>
        /// An <see cref="T:System.Collections.IEnumerator"/> object that can be used to iterate through the collection.
        /// </returns>
        System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
        {
            return ((IEnumerable<string>)this).GetEnumerator();
        }

        /// <summary>
        /// Returns an enumerator that iterates through the collection.
        /// </summary>
        /// <returns>
        /// A <see cref="T:System.Collections.Generic.IEnumerator`1"/> that can be used to iterate through the collection.
        /// </returns>
        public IEnumerator<T> GetEnumerator()
        {
            return _keys.GetEnumerator();
        }

        /// <summary>
        /// Compares the current object with another object of the same type.
        /// </summary>
        /// <param name="other">An object to compare with this object.</param>
        /// <returns>
        /// A 32-bit signed integer that indicates the relative order of the objects being compared.
        /// The return value has the following meanings:
        /// 
        /// <example>
        /// <code>
        /// Value              | Meaning
        /// ---------------------------------
        /// Less than zero     | This object is less than the <paramref name="other"/> parameter.
        /// Zero               | This object is equal to <paramref name="other"/>.
        /// Greater than zero  | This object is greater than <paramref name="other"/>.
        /// </code>
        /// </example>
        /// </returns>
        public int CompareTo(ValueChain<T> other)
        {
            if (other == null)
                return 1;
            return Chain.CompareTo(other.Chain);
        }

        /// <summary>
        /// Checks whether the current value is below the parent chain.
        /// </summary>
        /// <param name="parentChain">Parent value chain to check.</param>
        /// <returns>Returns true if the current value chain is below the parent chain, otherwise false.</returns>
        public bool IsBelowChain(ValueChain<T> parentChain)
        {
            if (parentChain._keys.Count >= _keys.Count)
                return false;

            for (int i = 0; i < parentChain._keys.Count; ++i)
            {
                if (!Compare(parentChain._keys[i], _keys[i]))
                    return false;
            }
            return true;
        }

        /// <summary>
        /// Creates a new ValueChain instance and combines it with the data from the current instance and from the given arguments.
        /// </summary>
        /// <param name="toCombine">A list of elements to combine the keys.</param>
        /// <returns>Returns the newly created instance.</returns>
        public ValueChain<T> Combine(params T[] toCombine)
        {
            IList<T> elements = new List<T>(_keys);
            elements.Add(toCombine);
            return new ValueChain<T>(elements);
        }

        /// <summary>
        /// Extracts a sub chain from the current value chain.
        /// </summary>
        /// <param name="index">The zero-based index at which the range starts.</param>
        /// <returns>Returns the replaced and new value chain.</returns>
        public ValueChain<T> SubChain(int index)
        {
            return new ValueChain<T>(_keys.GetRange(index, _keys.Count - index));
        }

        /// <summary>
        /// Extracts a sub chain from the current value chain.
        /// </summary>
        /// <param name="index">The zero-based index at which the range starts.</param>
        /// <param name="count">The number of elements in the range.</param>
        /// <returns>Returns the replaced and new value chain.</returns>
        public ValueChain<T> SubChain(int index, int count)
        {
            return new ValueChain<T>(_keys.GetRange(index, count));
        }

        /// <summary>
        /// Replaces the parent value chain with the given child value chain.
        /// </summary>
        /// <param name="parentChainToFind">Value chain which should be found in order to replace.</param>
        /// <param name="parentChainToInsert">Value chain which should replace the finding.</param>
        /// <returns>Returns the replaced and new value chain.</returns>
        public ValueChain<T> ReplaceParent(ValueChain<T> parentChainToFind, ValueChain<T> parentChainToInsert)
        {
            if (!IsBelowChain(parentChainToFind))
                return this;

            List<T> elements = new List<T>();
            elements.AddRange(parentChainToInsert._keys);
            elements.AddRange(_keys.GetRange(parentChainToFind.Count, _keys.Count - parentChainToFind.Count));
            return new ValueChain<T>(elements);
        }

        /// <summary>
        /// Serializes the current instance into its string representation.
        /// </summary>
        /// <returns>Returns the serialized data.</returns>
        internal virtual string Serialize()
        {
            return Chain;
        }

        private bool Compare(T left, T right)
        {
            return (left == right || left.Equals(right));
        }

        #endregion

        #region Events
        //--------------------------------------------------------------------
        // Events
        //--------------------------------------------------------------------

        #endregion
    }
}